package com.example.person.lister;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.example.person.entity.Person;
import com.example.person.entity.PersonVO;
import com.example.person.repository.PersonRepository;
import com.example.person.utils.IdUtils;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sytsnb@gmail.com
 * @date 2023 2023/3/12 4:20
 */
public class PersonReadLister implements ReadListener<PersonVO> {


    List<Person> list = new ArrayList<>();


    private PersonRepository personRepository;

    public PersonReadLister(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    @SneakyThrows
    @Override
    public void invoke(PersonVO personVO, AnalysisContext analysisContext) {
        Person person = new Person();
        BeanUtils.copyProperties(personVO, person);
        Thread.sleep(1);
        String id = IdUtils.getId();
        person.setId(id);
        System.out.println("personID = " + id);
        list.add(person);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        personRepository.saveAll(list);
    }
}
